package com.sky.tank.basic;

import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author sky
 * @version 1.0
 * @date 2022/5/19 20:59:56
 */
public class PlayVoice extends Thread {


    private String filename;//音频文件的路径
    public PlayVoice(String wavfile) {
        filename = wavfile;

    }

    @Override
    public void run() {
        //音频流
        AudioInputStream audioInputStream = null;
        try {
            InputStream in = this.getClass().getResourceAsStream("/static/music/" + filename);
            audioInputStream = AudioSystem.getAudioInputStream(in);
        } catch (Exception e1) {
            e1.printStackTrace();
            return;
        }

        AudioFormat format = audioInputStream.getFormat();
        SourceDataLine auline = null;
        DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);

        try {
            auline = (SourceDataLine) AudioSystem.getLine(info);
            auline.open(format);
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        auline.start();
        int nBytesRead = 0;
    //缓冲在byte中
        byte[] abData = new byte[1024];

        try {
            while (nBytesRead != -1) {
                //已循环形式读这个流
                nBytesRead = audioInputStream.read(abData, 0, abData.length);
                if (nBytesRead >= 0) {
                    auline.write(abData, 0, nBytesRead);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            auline.drain();
            auline.close();
        }

    }

}

